package x.ovo.wechat.bot.impl.core;

import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.thread.ThreadUtil;
import x.ovo.wechat.bot.core.Context;
import x.ovo.wechat.bot.core.event.SystemEvent;
import x.ovo.wechat.bot.impl.config.ClientConfig;

import java.util.concurrent.TimeUnit;

@Slf4j(topic = "Monitor")
public class Monitor implements Runnable {

    private final Context ctx = Context.INSTANCE;
    private final ClientConfig config = ClientConfig.get();

    @Override
    public void run() {
        log.info("心跳监控线程已启动");
        while (this.ctx.isRunning()) {
            ThreadUtil.safeSleep(TimeUnit.MINUTES.toMillis(1));
            long now = System.currentTimeMillis();
            long lastHeartbeat = this.ctx.getLastHeartbeat();
            log.debug("上次同步时间: {}, 间隔: {} ms", lastHeartbeat, now - lastHeartbeat);
            if (now - lastHeartbeat > TimeUnit.MINUTES.toMillis(this.config.getHeatbeatTimeout())) {
                log.warn("同步时间超过 {} 分钟，请检查网络连接是否正常", this.config.getHeatbeatTimeout());
                new SystemEvent("心跳同步时间超过 " + this.config.getHeatbeatTimeout() + " 分钟，进程即将退出").fire();
                System.exit(1);
            }
        }
    }
}
